package com.library.uiframework.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import com.library.uiframework.R;
import com.library.uiframework.widget.state.StateView;

/**
 * @author hongkai.qian
 * @version 1.0.0
 * @since 15-11-30
 */
public abstract class StateViewWithActionBarFragment extends ActionBarLayoutFragment implements StateView.OnConfigStateViewListener {

    private StateView mStateView;

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final int viewId = v.getId();
            if (viewId == R.id.loadingview_failed) {
                onRetryRequested();
            }
        }
    };

    @Override
    void initStateViewContainer(LayoutInflater inflater, StateView stateView, Bundle savedInstanceState) {
        super.initStateViewContainer(inflater, stateView, savedInstanceState);
        mStateView = stateView;
        View successView = onCreateContentView(inflater, mStateView, savedInstanceState);
        mStateView.setOnConfigStateViewListener(this);
        mStateView.setStateProperty(StateView.State.SUCCESS, successView);
    }

    @Override
    public int commonActionBarLayoutId() {
        return R.layout.uiframework_actionbar_layout_with_stateview;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mStateView.setState(originalState(), false);
    }

    @Override
    public void onLoadFinished() {
        super.onLoadFinished();
        if (mStateView.getCurrentState() == StateView.State.LOADING) {
            mStateView.showAnimation();
        }
    }

    protected void setState(StateView.State state) {
        mStateView.setState(state, true);
    }

    public void setStateProperty(StateView.State state, int layoutId) {
        mStateView.setStateProperty(state, layoutId);
    }

    /**
     * @return state view
     */
    public StateView getStateView() {
        return mStateView;
    }


    /**
     * ------------------    以下供派生类重载     --------------
     */


    /**
     * 重试请求
     */
    protected abstract void onRetryRequested();

    @Override
    public void onConfigStateView(View view, StateView.State state) {
        if (state == StateView.State.FAILED || state == StateView.State.NO_NETWORK) {
            view.setOnClickListener(mOnClickListener);
        }
    }


    /**
     * @return 初始状态, 默认loading
     */
    protected StateView.State originalState() {
        return StateView.State.LOADING;
    }

}
